package com.mtons.mblog.modules.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import com.mtons.mblog.base.lang.Consts;
import com.mtons.mblog.base.utils.ObjectConvertUtils;
import com.mtons.mblog.modules.pojo.Comment;
import com.mtons.mblog.modules.service.CommentService;
import com.mtons.mblog.modules.service.MessageService;
import com.mtons.mblog.modules.service.PostService;
import com.mtons.mblog.modules.vo.MessageVO;
import com.mtons.mblog.modules.vo.PostVO;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.io.IOException;

/**
 * @ClassName: PostMqHandler
 * @Auther: Jerry
 * @Date: 2020/5/15 14:54
 * @Desctiption: TODO
 * @Version: 1.0
 */
@Component
public class PostMqHandler {

    private Logger log = LoggerFactory.getLogger(PostMqHandler.class);

    @Autowired
    private MessageService messageService;

    @Autowired
    private PostService postService;
    @Autowired
    private CommentService commentService;

    @RabbitListener(queues = RabbitConstant.POST_QUEUE)
    public void handler(Message message, Channel channel) throws IOException {
        PostMqMessage postMqMessage = (PostMqMessage) ObjectConvertUtils.ByteToObject(message.getBody());

        log.info("PostMessageMqHandler -------> mq 收到一条消息： {}", JSONObject.toJSONString(postMqMessage));
        MessageVO nt = new MessageVO();
        nt.setPostId(postMqMessage.getPostId());
        nt.setFromId(postMqMessage.getFromUserId());
        nt.setEvent(postMqMessage.getEvent());
        PostVO p;
        switch (postMqMessage.getEvent()) {
            case Consts.MESSAGE_EVENT_FAVOR_POST:
                p = postService.get(postMqMessage.getPostId());
                Assert.notNull(p, "文章不存在");
                nt.setUserId(p.getAuthorId());
                break;
            case Consts.MESSAGE_EVENT_COMMENT:
                p = postService.get(postMqMessage.getPostId());
                Assert.notNull(p, "文章不存在");
                nt.setUserId(p.getAuthorId());
                // 自增评论数
                postService.identityComments(postMqMessage.getPostId());
                break;
            case Consts.MESSAGE_EVENT_COMMENT_REPLY:
                Comment c = commentService.findById(postMqMessage.getCommentParentId());
                Assert.notNull(c, "回复的评论不存在");
                nt.setUserId(c.getAuthorId());

                // 自增评论数
                postService.identityComments(postMqMessage.getPostId());
                break;
            default:
                nt.setUserId(postMqMessage.getToUserId());
        }
        messageService.send(nt);
        // 手动ack
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
